import { View, Text, Image } from "@tarojs/components";
import Taro, { useLoad, useUnload } from "@tarojs/taro";
import { Button, Cell, CellGroup, NavBar } from "@nutui/nutui-react-taro";
import { Share, More, Cart, ArrowLeft, Close } from '@nutui/icons-react-taro'
import { c } from "../../../common";
import { useEffect, useRef, useState } from "react";
// import CountdownTimer from './components/time'

import { getParams, navigateTo } from "../../../common/_";
// import { Right } from "@nutui/icons-react-taro";

import { endExam, startExam } from "../../../api/ceshi";
import { baseUrl } from "../../../utils/request";
import { iconClock } from "../../../assets/files";
import "./index.scss";

let intervalId = null
export default function Test() {

  const [cur, setCur] = useState(0)
  const [statusBarHeight, setStatusBarHeight] = useState(47)
  const [userExamId, setUserExamId] = useState("");

  const [questionType, setQuestionType] = useState([
    {
      id: 1,
      name: "单选题",
      color: '#6486FF',
      bgColor: 'rgba(65, 95, 255, 0.05)'
    },
    {
      id: 2,
      name: "多选题",
      color: '#44C0E8',
      bgColor: 'rgba(65, 221, 255, 0.05)'
    },
    {
      id: 3,
      name: "判断题",
      color: '#FF8964',
      bgColor: 'rgba(255, 145, 65, 0.05)'
    },
  ]);
  const [questionList, setQuestionList] = useState([]);

  useEffect(() => {
    getRequest()
  }, [])

  async function getRequest() {
    Taro.showLoading()
    const { data } = await startExam({questionBankTypeid:getParams().id})

    data.questionResponses.forEach(v => {
      v.questionOptionIds = []
    })
    setQuestionList(data.questionResponses)
    setUserExamId(data.userExamId)
    setSeconds(data.examTotal * 60)
    Taro.hideLoading()
  }

  const [seconds, setSeconds] = useState(1800);
  useEffect(() => {
    intervalId = setInterval(() => {
      setSeconds(seconds => seconds - 1);
    }, 1000);
    return () => {
      clearInterval(intervalId)
    };
  }, []);


  const clearIntervalFn = () => {
    // 清除定时器
    if (intervalId) {
      clearInterval(intervalId);
      intervalId = null;
    }
  };

  useEffect(() => {
    if (seconds === 0) {
      Taro.showModal({
        title: "测试时间已到，将为您交卷",
        showCancel: false,
        complete(res) {
          console.log(res);
          if (res.confirm) {
            console.log("交卷");
            submit()
          }
        }
      })
    }



  }, [seconds])

  useEffect(() => {
    Taro.getSystemInfoAsync({
      success(res) {
        console.log(res);
        setStatusBarHeight(res.statusBarHeight)
      }
    })
  }, [])


  function matchType(type) {
    for (let index = 0; index < questionType.length; index++) {
      const element = questionType[index];
      if (element.id === type) {
        return element
      }

    }

  }

  function nextRequest(item) {
    if (item.questionOptionIds.length == 0) {
      Taro.showToast({
        title:'请点击选择答案',
        icon:'none'
      })
      return
    }

    let curren = cur
    curren = curren + 1
    setCur(curren)
  }

  async function submit() {
    let questionOptionIds = []
    questionList.forEach(v => {
      questionOptionIds.push({ 'questionId': v.id, "questionOptionIds": v.questionOptionIds })
    })

    let params = {
      questionOptionIds,
      userExamId
    }
    // console.log(params);
    Taro.showLoading()
    const { success, data } = await endExam(params)
    Taro.hideLoading()
    if (success) {
      clearIntervalFn()
      navigateTo('/packageA/pages/test-result/index', {
        data
      })
    }
  }


  function setAnswer(item, index, v) {
    let list = JSON.parse(JSON.stringify(questionList))


    if (item.questionType === 1 || item.questionType === 3) {
      //单选和判断题
      list[index].questionOptionIds = []
      list[index].questionOptionIds.push(v.id)
    } else if (item.questionType === 2) {
      //多选
      if (!list[index].questionOptionIds.includes(v.id)) {
        list[index].questionOptionIds.push(v.id)
      } else {
        list[index].questionOptionIds.forEach((element, j) => {
          if (element === v.id) {
            console.log(element);
            console.log(v.id);

            list[index].questionOptionIds.splice(j, 1)
          }
        });
      }

    }
    // console.log(list);
    setQuestionList(list)

  }

  function _handleback() {
    console.log(questionList);
    // return;
    if (questionList[0].questionOptionIds.length === 0) {
      Taro.navigateBack({
        delta: 1
      })
      return
    }
    Taro.showModal({
      title: "返回将自动提交，确定返回?",
      complete(res) {
        console.log(res);
        if (res.confirm) {
          submit()
        }
      }
    })
  }

  const formatTime = (time) => {
    const hours = Math.floor(time / 3600);
    const minutes = Math.floor((time % 3600) / 60);
    const secs = time % 60;
    return [hours, minutes, secs]
      .map(num => num < 10 ? '0' + num : num)
      .filter((num, i) => i > 0 || num !== '00')
      .join(':');
  };

  return (
    <View className="wrap">
      <NavBar
        style={{ backgroundColor: '#fff', position: 'absolute', left: 0, top: statusBarHeight }}
        back={
          <>
            <ArrowLeft />
          </>
        }
        onBackClick={(e) => _handleback()}
      >
        <span>我要测试</span>
      </NavBar>

      <View className="daoWrap" style={{ paddingTop: statusBarHeight + 60 }}>
        <View className="clockWrap">
          <Image className="clockIcon" src={iconClock} />
          <Text>
            {seconds > 0 ? formatTime(seconds) : '00:00:00'}
          </Text>
        </View>
        <View>
          <Text className="cur">{cur + 1}</Text>
          <Text className="allLength">{`/${questionList.length}`}</Text>
        </View>

      </View>

      {questionList?.map((item, index) => {
        return (
          <>
            {
              cur === index &&
              <View className="reWrap" key={index} >
                <View className="reTypeWrap">
                  {/* <Text className="reTypeText" style={{ color: matchType(item.questionType).color, backgroundColor: matchType(item.questionType).bgColor }}>{matchType(item.questionType).name}</Text> */}
                  <View className="bss"></View>
                  <Text className="questionType" style={{ }}>{matchType(item.questionType).name}</Text>
                  <View className="ftype">
                    <Text>{item.questionTypeName}</Text>
                  </View>
                </View>
                <View className="reTitWrap">
                  <Text className="questTit">{item.questionSubject}</Text>

                  <View className="reItemWrap">
                    {
                      item?.optionMiniResponses.map((v, i) => {
                        return (
                          <View className="reItem" key={i} onClick={() => setAnswer(item, index, v)}>
                            <View className={item.questionOptionIds.includes(v.id) ? "tagWrapSelect" : "tagWrap"}>
                              <Text style={{ color: item.questionOptionIds.includes(v.id) ? "#fff" : '#212121' }} className="tagName">{v.questionOption}</Text>
                            </View>
                            <View style={{ flex: 1 }}>
                              {
                                v.optionType === 1 ?
                                  <Text className="reContent">{v.optionContent}</Text>
                                  :
                                  <Image className="ansImgSty" src={baseUrl + v.optionContent} />
                              }
                            </View>
                          </View>
                        )
                      })
                    }
                  </View>

                </View>

                {
                  cur === questionList.length - 1 ?
                    <View className="btnWrap" onClick={() => {
                      if (item.questionOptionIds.length == 0) {
                        return
                      }
                      submit()
                    }}>
                      <Button type="info" block size="large" disabled={item.questionOptionIds.length == 0}>交卷</Button>
                    </View>
                    :
                    <View className="btnWrap" onClick={() => nextRequest(item)}>
                      <Button
                        color={item.questionOptionIds.length == 0 ? "#F0F0F0" : "#6486FF"}
                        style={{ color: item.questionOptionIds.length == 0 ? "#212121" : "#fff" }}
                        block
                        size="large"
                        disabled={item.questionOptionIds.length == 0}>
                        下一题
                      </Button>
                    </View>
                }
              </View>

            }
          </>
        );
      })}
    </View>
  );
}
